package com.wq.httpclientcore.service.impl;

import com.wq.httpclientcore.entities.po.DbConnectionConfig;
import com.wq.httpclientcore.entities.po.DbQueryConfig;
import com.wq.httpclientcore.entities.req.query.DbQueryConfigREQ;
import com.wq.httpclientcore.mapper.DbQueryConfigMapper;
import com.wq.httpclientcore.service.DbConnectionConfigService;
import com.wq.httpclientcore.service.DbQueryConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wq.httpclientcore.utils.QueryWrapperBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 数据库查询配置 服务实现类
 *
 * @author wangqi
 * @since 2025-03-18 09:05:42
 */
@Service
public class DbQueryConfigServiceImpl extends ServiceImpl<DbQueryConfigMapper, DbQueryConfig> implements DbQueryConfigService {

    @Autowired
    private DbConnectionConfigService dbConnectionConfigService;

    @Override
    public List<DbQueryConfig> list(DbQueryConfigREQ req) {
        req.setOrderByField("updated_at");
        LambdaQueryWrapper<DbQueryConfig> queryWrapper = QueryWrapperBuilder.queryWrapper(DbQueryConfig.class, req);
        List<DbQueryConfig> dbQueryConfigList = list(queryWrapper);
        enrichQueryConfigWithConnectionConfig(dbQueryConfigList);
        return dbQueryConfigList;
    }

    @Override
    public Page<DbQueryConfig> pageList(DbQueryConfigREQ req) {
        req.setOrderByField("updated_at");
        LambdaQueryWrapper<DbQueryConfig> queryWrapper = QueryWrapperBuilder.queryWrapper(DbQueryConfig.class, req);
        Page<DbQueryConfig> page = Page.of(req.getPageNo(), req.getPageSize());
        Page<DbQueryConfig> result = page(page, queryWrapper);
        enrichQueryConfigWithConnectionConfig(result.getRecords());
        return result;
    }

    private void enrichQueryConfigWithConnectionConfig(List<DbQueryConfig> queryConfigList) {
        List<DbConnectionConfig> dbConfigList = dbConnectionConfigService.list();
        List<Long> dbIds = dbConfigList.stream().map(DbConnectionConfig::getId).collect(Collectors.toList());
        Map<Long, DbConnectionConfig> longDbConfigMap = dbConnectionConfigService.id2PO(dbIds);
        queryConfigList.forEach(queryConfig -> {
            queryConfig.setDbConnectionConfig(longDbConfigMap.get(queryConfig.getDbConnectionId()));
        });
    }
}
